package de.idgard.android.addon.ui.services.impl;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.webkit.WebView;
import de.idgard.android.addon.ui.services.BrowserTabService;
import de.idgard.android.addon.ui.services.BrowserUtilityService;
import de.idgard.android.addon.ui.services.ZircoToIDGardAPI;

/**
 * 
 * @author ckaratza
 * 
 */

class BrowserTabServiceImpl implements BrowserTabService {

	private BrowserUtilityService browserUtilityService;

	public void setBrowserUtilityService(
			BrowserUtilityService browserUtilityService) {
		this.browserUtilityService = browserUtilityService;
	}

	ZircoToIDGardAPI api;

	public void setZircoToIDGardAPI(ZircoToIDGardAPI api) {
		this.api = api;
	}

	private void invokeOnView(WebView obj, String action) {
		try {
			WebView.class.getMethod(action).invoke(obj, null);
		} catch (Exception ex) {
			throw new RuntimeException(ex.getMessage());
		}
	}

	private List<String> removeCurrentTabsAndReturnUrls() {

		if (api.isMfindDialogVisible()) {
			api.closeFindDialog();
		}
		List<String> urls = new ArrayList<String>();
		List<WebView> views = api.getContainersWebViews();
		if (!views.isEmpty()) {
			for (WebView view : views) {
				invokeOnView(view, "onPause");
				synchronized (api.getViewFlipper()) {
					String url = view.getUrl();
					if (url == null
							|| "".equals(url)
							|| browserUtilityService.checkIfIDStartPage(url)
							|| browserUtilityService
									.checkIfIDGardDomainOrigination(url)) {
						continue;
					}
					urls.add(view.getUrl());
				}
			}
			int size = views.size();
			api.addTab(true, size - 1);
			api.getViewFlipper().setDisplayedChild(size - 1);
			for (int i = 0; i < size; i++) {
				api.removeCurrentTab();
			}
		}
		return urls;
	}

	@Override
	public void closeAllTabsInOnModeBrowserState() {
		removeCurrentTabsAndReturnUrls();
	}

	@Override
	public void reloadAllTabs() {
		for (WebView view : api.getContainersWebViews()) {
			invokeOnView(view, "onPause");
			synchronized (api.getViewFlipper()) {
				view.reload();
			}
		}
	}

	@Override
	public void addNewTab() {
		api.addNewTab();
	}
}
